package com.cqeec.waimai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqeec.waimai.common.R;
import com.cqeec.waimai.entity.Category;
import com.cqeec.waimai.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//分类管理页面
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;
//    分页查询
    @GetMapping("/page")
    public R<Page> getPage(int page,int pageSize){
        Page<Category> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        categoryService.page(pageInfo,wrapper);
        return R.success(pageInfo);
    }
//    新增分类
    @PostMapping
    public R<String> addCategory(@RequestBody Category category){
        categoryService.save(category);
        return R.success("新增分类成功");
    }
//    回显
    @GetMapping("/{id}")
    public R<Category> getById(@PathVariable("id")Long id){
        Category byId = categoryService.getById(id);
        return R.success(byId);
    }
//    修改
    @PutMapping
    public R<String> updateByCategory(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改分类成功");
    }
    @GetMapping("list")
    public R<List<Category>> getListCategory(Category category){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(category.getType()!=null,Category::getType,category.getType());
        wrapper.orderByAsc(Category::getSort);
        List<Category>list = categoryService.list(wrapper);
        return R.success(list);
    }
//    删除分类
    @DeleteMapping
    public R<String> delete(Long id){
        categoryService.removeCategory(id);
        return R.success("删除分类成功");
    }
}
